package org.stvd.controller.admin;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Guids;
import org.stvd.entities.admin.Params;
import org.stvd.service.admin.GuidsService;
import org.stvd.service.admin.ParamsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 参数管理-控制类
 * @author houzx
 */
@Api(tags = "系统参数接口类")
@Controller
@RequestMapping("/admin/params")
public class ParamsController extends BaseController {

    @Autowired
    ParamsService paramsService;
    @Autowired
    private GuidsService guidsService;
    
    @Value("${top_guid}")
    private String topGuid = "";
    
    private String tmpURL = "/admin/params/";
    
    /**
     * 参数管理请求
     * @param params
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "management")
    public String onParamManageLoad(@ModelAttribute("params") Params params) {
        if(!StringUtil.isEmpty(request.getParameter("gid"))) {
            params.setGuid(request.getParameter("gid"));
        }
        if(StringUtil.isEmpty(params.getGuid())) {
            params.setGuid(StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid);
        }
        loadParamResource(params);
        return tmpURL + "ParamsManagement.html";
    }
    
    @ApiIgnore
    @PostMapping(value = "management")
    public String onParamManageAction(@ModelAttribute("params") Params params) {
        loadParamResource(params);
        return tmpURL + "ParamsManagement.html";
    }

    // 加载系统参数资源
    public void loadParamResource(Params params) {
        QueryResult<Params> queryResult = paramsService.getParamQueryResult((pageNo - 1) * pageSize, pageSize,
            params.getParamName(), params.getGuid());
        map.put("queryResult", queryResult);
        map.put("guidsList", guidsService.listGuidByUserId(SecurityUserHolder.getCurrentUserId()));
        map.put("guids", guidsService.findByPk(Guids.class, StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid));
    }
    
    /**
     * 参数新增
     * @param guid
     * @param params
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "add/{guid}")
    public String onAddLoad(@PathVariable String guid, 
        @ModelAttribute("params") Params params) {
        params.setGuid(guid);
        return tmpURL + "ParamsAdd.html";
    }

    @ApiOperation("新增参数信息")
    @Log(title = "新增参数信息", businessType = BusinessType.INSERT)
    @PostMapping(value = "add")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onAddAction(
        @Valid @ModelAttribute("params") Params params, BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        if("1".equals(params.getParamType())) {
            params.setGuid("");
        }
        params.setParamId(StringUtil.getRandomUUID());
        paramsService.insert(params);
        map.clear();
        
        result.setMsg("新增成功！");
        return result;
    }

    /**
     * 参数修改
     * @param paramId
     * @return
     */
    @ApiIgnore
    @GetMapping(value = "edit/{paramId}")
    public String onEditLoad(@PathVariable String paramId) {
        map.put("params", paramsService.findByPk(Params.class, paramId));
        map.put("guidsList", guidsService.listGuidByUserId(SecurityUserHolder.getCurrentUserId()));
        map.put("guids", guidsService.findByPk(Guids.class, StringUtil.isEmpty(topGuid) ? Consts.GUID :topGuid));
        return tmpURL + "ParamsEdit.html";
    }

    @ApiOperation("修改参数信息")
    @Log(title = "修改参数信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "edit")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onEditAction(
        @Valid @ModelAttribute("params") Params params, BindingResult bindingResult) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        if("1".equals(params.getParamType())) {
            params.setGuid("");
        }
        paramsService.update(params);
        map.clear();
        
        result.setMsg("修改成功！");
        return result;
    }
    
    /**
     * 参数删除
     * @param paramId
     * @return
     */
    @ApiOperation("删除参数信息")
    @Log(title = "删除参数信息", businessType = BusinessType.DELETE)
    @PostMapping(value = "del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onDelete(String paramId, String paramName){
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        try {
            paramsService.delete(Params.class, paramId);
            result.setMsg("参数‘" + paramName + "’删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setError("删除参数" + paramName + "失败！<br/>失败原因：" + e.getMessage());
        }
        return result;
    }
}
